<template>
<div class="app-container">
  <div class="pb20">
    <!-- <el-button type="danger" icon="el-icon-delete" v-if="nodePower.includes('del')" :disabled="!!!delIds.length" @click="del">{{$t('common.deletes')}}</el-button> -->
    <el-popover class="mr10" placement="bottom" trigger="click" :width="device==='mobile' ? '320' : ''">
      <ProForm ref="searchForm" :config="SFC" />
      <el-button type="primary" @click="onSearch('Orders',{indent_type: types[type]})">{{ $t('common.confirm') }}</el-button>
      <el-button v-if="device==='desktop'" slot="reference" type="primary" icon="el-icon-search">{{ $t('common.search') }}</el-button>
      <el-button v-else slot="reference" type="primary" icon="el-icon-search" />
    </el-popover>
    <el-button type="primary" icon="el-icon-refresh" plain @click="reset('searchForm', 'Orders', {indent_type: types[type]})" />
    <el-radio-group v-model="type" class="ml10" @change="toggType">
      <el-radio-button v-for="(i, index) in 3" :key="i" :label="index">{{ $t('order.type'+index) }}</el-radio-button>
    </el-radio-group>
  </div>
  <el-form label-suffix="：" inline>
    <el-form-item v-for="(item, index) in sales" :key="index" :label="$t('order.sales'+index)">{{ item }}</el-form-item>
  </el-form>

  <!--  -->
  <ProTable index border :is-loading="isLoading" :data="list.map(item=>({...item,payment_at_copy:item.payment_at}))" :page="page" :column="column" @page-change="onPageChange('Orders', $event, {indent_type: types[type]})" @selection-change="delIds=$event.map(({order_id})=>order_id)">
    <template #order_details="{row}">
      <ProImage v-if="row.order_details.length" :src="row.order_details.map(({product_img})=>product_img)" :title="row.order_details.map(({product_name})=>product_name).join('\n')" />
      <div v-else>--</div>
    </template>
    <template #indent_type="{row}">{{ $t('order.type'+row.indent_type) }}</template>
    <template #payment_status="{row}">{{ $t('order.ps'+row.payment_status) }}</template>
    <template #payment_mode="{row}">{{ $t('order.pt'+row.payment_mode) }}</template>
    <template #payment_at="{row}">
      <div class="df" v-if="$route.query.order==='true'">
        <el-date-picker :placeholder="$t('order.payat_err')" v-model="row.payment_at_copy" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" :disabled="row.payment_status<3" />
        <el-button type="primary" :loading="isLoadPayat && curId===row.order_id" @click="updatePayat(row)" :disabled="row.payment_status<3">確定</el-button>
      </div>
      <span v-else>{{ row.payment_at || '--' }}</span> 
    </template>
    <template #control="{scope:{row}}">
      <el-link v-if="nodePower.includes('view')" class="row-control-item" :class="$store.state.app.size" type="primary" :underline="false" @click="view(row)">{{ $t('common.view') }}</el-link>
      <el-dropdown @command="handleCommand($event, row)">
        <el-link class="row-control-item" :class="$store.state.app.size" type="primary" :underline="false">{{ $t('common.more') }}<i class="el-icon-arrow-down el-icon--right" /></el-link>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="getRecord">{{ $t('order.control_record') }}</el-dropdown-item>
          <el-dropdown-item v-if="nodePower.includes('pay')" command="pay" :disabled="row.payment_status>=3">{{ $t('order.pay') }}</el-dropdown-item>
          <el-dropdown-item v-if="nodePower.includes('download')" command="rai">{{ $t('order.' + (row.payment_status<3 ? 'invoice' : 'receipt')) }}</el-dropdown-item>
          <el-dropdown-item v-if="nodePower.includes('del')" command="del" divided>
            <el-link class="row-control-item" :class="$store.state.app.size" type="danger" :underline="false">{{ $t('common.del') }}</el-link>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </template>
  </ProTable>

  <!--  -->
  <el-dialog :title="$t('order.detail')" :visible.sync="show" :width="device==='desktop' ? '800px' : '100%'" :close-on-click-modal="false" @closed="resetDetail">
    <div v-if="detail">
      <!--  -->
      <h4>{{ $t('order.indType'+detail.indent_type) }}</h4>
      <el-card v-for="(goods, index) in detail.order_details" :key="index" class="mb20">
        <div class="goods">
          <el-row>
            <el-col :span="device==='desktop' ? 16 : 24">
              <el-row>
                <el-col :span="device==='desktop' ? 3 : 4">
                  <ProImage :src="goods.product_img" />
                </el-col>
                <el-col :span="device==='desktop' ? 21 : 20">
                  <div class="mlr20">
                    <div class="goods-title">{{ goods.product_name }}</div>
                    <div class="goods-txt">{{ $t('common.spec') }}：{{ goods.product_specs || '--' }}</div>
                    <div class="goods-txt df jcsb"><span>{{ $t('offlineOrder.uniPrice') }}：${{ goods.product_price }}</span><span>x{{ goods.product_number }}</span></div>
                    <div v-if="goods.order_logistics.length && goods.order_logistics[0].logistics_number" class="goods-txt">{{ `${goods.order_logistics[0].logistics_number}（${$t('order.logistics_no')}）` }}</div>
                  </div>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="device==='desktop' ? 8 : 24">
              <div class="btns" :class="{mt20: device==='mobile'}">
                <!-- 產品 -->
                <template v-if="detail.indent_type===1">
                  <!-- 添加物流單號 -->
                  <el-popover v-if="nodePower.includes('logistics')" class="mr10" placement="bottom" trigger="click" @show="showLogiInp(goods.order_logistics[0], index)" @hide="hideLogiInp">
                    <div class="df">
                      <el-input v-model="logiForm.logistics_number" class="mr10" :placeholder="$t('common.enter')" />
                      <el-button type="primary" :loading="isLoadLogi" @click="logistics">{{ $t('common.confirm') }}</el-button>
                    </div>
                    <!-- 自取不填  發貨不填  未支付不填 -->
                    <el-button slot="reference" type="primary" :disabled="detail.receiving_type==2||detail.payment_status<=2 || 4<= detail.payment_status || goods.logistics_status>0">{{ $t('order.logistics') }}</el-button>
                  </el-popover>
                  <!-- 確認收貨 -->
                  <!-- 已支付都可以確認支付 -->
                  <el-button v-if="nodePower.includes('complete')" type="primary" :disabled="detail.payment_status<=2 || 4<= detail.payment_status" @click="rac(goods.details_id, index)">{{ $t('order.received') }}</el-button>
                </template>
                <!-- 預約 -->
                <template v-if="detail.indent_type===2">
                  <!-- 修改預約時間 -->
                  <el-popover v-if="nodePower.includes('appotime')" v-model="showAppoInp" class="mr10" placement="bottom" trigger="manual" @show="showAppoSlt" @hide="hideAppoSlt">
                    <div class="df aic">
                      <el-date-picker v-model="appoForm.order_time" class="mr10" type="datetime" :placeholder="$t('common.selectPh')" :picker-options="pickerOptions" value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" />
                      <el-button type="primary" :loading="isLoadAppo" @click="appoTime">{{ $t('common.confirm') }}</el-button>
                      <i class="el-icon-close ml10" @click="showAppoInp=false" />
                    </div>
                    <!--支付已取消和完成不可改 -->
                    <el-button slot="reference" type="primary" :disabled="4<= detail.payment_status" @click="showAppoInp=true">{{ $t('order.appoTime') }}</el-button>
                  </el-popover>
                  <!-- 確認完成 -->
                  <!-- 已支付都可以確認支付 -->
                  <el-button v-if="nodePower.includes('complete')" type="primary" :disabled="detail.payment_status<=2 || 4<= detail.payment_status" @click="rac(goods.details_id, index)">{{ $t('order.complete') }}</el-button>
                </template>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <!--  -->
      <el-descriptions :title="$t('order.baseInfo')" :column="1" border>
        <el-descriptions-item :label="$t('order.order_no')">{{ detail.order_no }}</el-descriptions-item>
        <el-descriptions-item :label="$t('order.type')">{{ $t('order.type'+detail.indent_type) }}</el-descriptions-item>
        <el-descriptions-item :label="$t('order.payment_status')">{{ $t('order.ps'+detail.payment_status) }}</el-descriptions-item>
        <el-descriptions-item :label="$t('order.order_remark')">{{ detail.order_remark || '--' }}</el-descriptions-item>
        <template v-if="detail.indent_type===1">
          <el-descriptions-item :label="$t('order.receiving_type')">{{ $t('order.rt'+detail.receiving_type) }}</el-descriptions-item>
          <el-descriptions-item v-if="detail.receiving_type===2" :label="$t('order.spTime')">{{ detail.order_time }}</el-descriptions-item>
        </template>
        <el-descriptions-item v-if="detail.indent_type===2" :label="$t('order.apoTime')">{{ detail.order_time }}</el-descriptions-item>
        <!-- <el-descriptions-item :label="$t('common.created_at')">{{detail.created_at}}</el-descriptions-item>
            <el-descriptions-item :label="$t('common.updated_at')">{{detail.updated_at}}</el-descriptions-item> -->
      </el-descriptions>

      <!--  -->
      <el-descriptions class="mtb20" :title="$t('order.contact')" :column="1" border>
        <el-descriptions-item v-for="item in contact" :key="item" :label="$t('order.'+item)">{{ detail[item] }}</el-descriptions-item>
        <template v-if="detail.indent_type===1 && detail.receiving_type===1">
          <el-descriptions-item :label="$t('order.delivery_area')">{{ detail.delivery_area }}</el-descriptions-item>
          <el-descriptions-item :label="$t('order.delivery_address')">{{ detail.delivery_address }}</el-descriptions-item>
        </template>
      </el-descriptions>

      <!--  -->
      <el-descriptions :title="$t('order.payInfo')" :column="1" border>
        <el-descriptions-item :label="$t('order.payment_mode')">{{ $t('order.pt'+detail.payment_mode) }}</el-descriptions-item>
        <el-descriptions-item :label="$t('order.order_money')">{{ detail.order_money }}</el-descriptions-item>
        <el-descriptions-item :label="$t('order.payment_at')">{{ detail.payment_at || '--' }}</el-descriptions-item>
      </el-descriptions>
    </div>
  </el-dialog>
  <!-- 操作记录 -->
  <el-dialog :title="$t('order.control_record')" :visible.sync="showRecord" :width="device==='desktop' ? '1000px' : '100%'" :close-on-click-modal="false">
    <div class="df aic mb20">
      <h4>{{ $t('order.record_type') }}：</h4>
      <el-select v-model="recordType" :placeholder="$t('common.selectPh')" clearable>
        <el-option v-for="i in 4" :key="i" :label="$t(`order.recordType${i+5}`)" :value="i+5"></el-option>
      </el-select>
    </div>
    <ProTable index border :is-loading="recordLoad" :data="recordList" :column="recordCol" :page="recordPage" @page-change="onRecordPageChange">
      <template #activity_value="{row}"><span>{{ language==='zh' ? row.activity_value : row.en_activity_value }}</span></template>
      <template #activity_type="{row}"><span>{{ $t(`order.recordType${row.activity_type}`) }}</span></template>
    </ProTable>
  </el-dialog>
</div>
</template>

<script>
import { mapGetters } from 'vuex'
import { log, order } from '@/form'
import { getArea, addLogistic, editAppoTime, completeOrder, confirmPay, delOrder, DlFile, getStore, controlRecord, editPaymentat } from '@/api'
import { recursion } from '@/utils'
import paging from '@/mixins/paging'
// import area from '@/json/area.json'
export default {
  name: 'OrderList',
  mixins: [paging],
  data() {
    return {
      SFC: order.SFC,
      delIds: [],
      isLoading: false,
      type: 0,
      types: [[1, 2], [1], [2]],
      sales: [],
      column: {
        order_no: 'order.order_no',
        order_details: 'order.goods',
        delivery_name: 'order.user',
        indent_type: 'order.type',
        payment_status: 'order.payment_status',
        payment_mode: 'order.payment_mode',
        order_money: 'order.money',
        payment_at: 'order.payTime'
      },
      show: false,
      detail: null,
      isLoadLogi: false,
      logiIndex: '',
      logiForm: { logistics_number: '' },
      showAppoInp: false,
      isLoadAppo: false,
      appoForm: { order_time: '' },
      contact: ['delivery_name', 'delivery_phone', 'delivery_mail'],
      payLab: ['payment_mode', 'payment_status', 'order_money'],
      checked: [],
      start_time: '',
      end_time: '',
      showRecord: false,
      recordLoad: false,
      recordType: '',
      record_id: '',
      recordList: [],
      recordPage: {
        current: 1,
        size: 10,
        total: 0
      },
      recordCol: {
        activity_value: 'order.record_value',
        activity_type: 'order.record_type',
        admin_name: 'coupon.admin',
        created_at: 'order.record_date',
      },
      curId: '',
      isLoadPayat: false,
    }
  },
  created() {
    this.getStore()
  },
  mounted() {
    this.init()
    this.getList('Orders', { indent_type: [1, 2] })
  },
  computed: {
    ...mapGetters(['language', 'device']),
    pickerOptions() {
      return {
        // // 預約時間過期禁用(日期)
        disabledDate: time => {
          const day = time.getDay()
          const index = (day + 6) % 7
          return time.getTime() <= (Date.now() - 24 * 60 * 60 * 1000) || this.checked[index] === 0
        },
        // 預約時間過期禁用（时分)
        selectableRange: this.selectableRange()
      }
    },
  },
  watch: {
    recordType(val) {
      this.getRecord({ order_id: this.record_id })
    }
  },
  methods: {
    init() {
      getArea().then(({ results }) => {
        const { result } = recursion({ data: results, match: [['label', 'value'], ['area_name', 'area_name']] })
        this.$set(this.SFC.formItems[0].item.attr, 'options', result)
      })
      // const options = this.area.areas.map(ai => {
      //   const label = this.==='zh' : row.activity_value : row.en_==='zh' ? ai.zh_name : ai.en_name
      //   return {
      //     label, value:label, children: this.area.districts.filter(di => di.parent_id===ai.id).map(di => {
      //       const label = this.==='zh' : row.activity_value : row.en_==='zh' ? di.zh_name : di.en_name
      //       return {
      //         label, value:label, children: this.area.blocks.filter(bi => bi.d_id === di.id).map(bi => {
      //           const label = this.==='zh' : row.activity_value : row.en_==='zh' ? bi.zh_name : bi.en_name
      //           return {label, value: label}
      //         })
      //       }
      //     })
      //   }
      // })
      // this.$set(this.SFC.formItems[0].item.attr, 'options', options)
    },
    // 切換類型
    toggType(e) {
      this.getList('Orders', { indent_type: this.types[e] })
    },
    // 操作
    handleCommand(funcName, row) {
      this[funcName](row)
    },
    // 查看
    view(row) {
      this.detail = row
      this.show = true
    },
    // 物流輸入框
    showLogiInp({ logistics_id, details_id }, index) {
      Object.assign(this.logiForm, { logistics_id, details_id })
      this.logiIndex = index
    },
    hideLogiInp() {
      this.logiForm = { logistics_number: '' }
      this.logiIndex = ''
    },
    // 添加物流單號
    async logistics() {
      if (!this.logiForm.logistics_number) return this.$message({ message: this.$t('order.logi_err'), type: 'warning' })
      try {
        this.isLoadLogi = true
        await addLogistic(this.logiForm)
        this.$set(this.detail.order_details[this.logiIndex].order_logistics[0], 'logistics_number', this.logiForm.logistics_number)
        this.$set(this.detail.order_details[this.logiIndex], 'logistics_status', 1)
        this.$message({ message: this.$t('common.success'), type: 'success' })
        this.hideLogiInp()
      } catch (error) {

      } finally {
        this.isLoadLogi = false
      }
    },
    // 獲取店鋪信息
    async getStore() {
      const { results } = await getStore()
      const list = results.workday
      // console.log(list)
      for (const i in list) {
        if (list[i].is_open * 1 === 1) {
          this.checked.push(1)
          this.start_time = list[i].start_time
          this.end_time = list[i].end_time
        } else {
          this.checked.push(0)
        }
      }
    },
    // 預約時間選擇
    showAppoSlt() {
      const { order_id, order_time } = this.detail
      Object.assign(this.appoForm, { order_id, order_time })
    },
    hideAppoSlt() {
      this.appoForm = { order_time: '' }
    },
    // disabledDate(e) {
    //   return (Date.now() - 24 * 60 * 60 * 1000) > new Date(e).getTime()
    // },
    // 預約時間過期禁用
    selectableRange(e) {
      return this.start_time + '-' + this.end_time
    },
    // 修改預約時間
    async appoTime() {
      if (!this.appoForm.order_time) return this.$message({ message: this.$t('order.appo_err'), type: 'warning' })
      try {
        this.isLoadAppo = true
        await editAppoTime(this.appoForm)
        this.detail.order_time = this.appoForm.order_time
        this.$message({ message: this.$t('common.success'), type: 'success' })
        this.hideAppoSlt()
      } catch (error) {

      } finally {
        this.isLoadAppo = false
        this.showAppoInp = false
      }
    },
    // 確認收貨/完成
    rac(details_id, index) {
      this.asyncMsg(async(instance, done) => {
        instance.confirmButtonLoading = true
        try {
          await completeOrder({ product_type: this.detail.indent_type, details_id })
          this.$set(this.detail, 'payment_status', 5)
          this.$set(this.detail.order_details[index], 'logistics_status', 2)
          done()
        } catch (error) {

        } finally {
          instance.confirmButtonLoading = false
        }
      }, this.$t('order.' + (this.detail.indent_type === 1 ? 'received_con' : 'complete_con')))
    },
    // 關閉詳情彈窗重置
    resetDetail() {
      this.showAppoInp = false
    },
    // 操作记录
    async getRecord({ order_id }) {
      this.record_id = order_id
      this.showRecord = true
      this.recordLoad = true
      try {
        const { results:{data, count} } = await controlRecord({page: this.recordPage.current, limit:this.recordPage.size, order_id, activity_type: this.recordType})
        this.recordList = data
        this.recordPage.total = count
      } catch (error) {

      } finally {
        this.recordLoad = false
      }
    },
    onRecordPageChange() {
      this.getRecord({ order_id: this.record_id })
    },
    // 確認支付
    pay({ order_id }) {
      this.asyncMsg(async(instance, done) => {
        instance.confirmButtonLoading = true
        try {
          await confirmPay({ order_id })
          const { current, size } = this.page
          this.getList('Orders', { indent_type: this.types[this.type], page: current, limit: size })
          done()
        } catch (error) {

        } finally {
          instance.confirmButtonLoading = false
        }
      }, this.$t('order.pay_con'))
    },
    // 下载收据/发票
    async rai({ order_id }) {
      try {
        // const result = await DlFile({order_id})
        // let url = URL.createObjectURL(result)
        const url = process.env.VUE_APP_BASE_API + '/generateInvoiceWeb?order_id=' + order_id
        window.open(url, '_blank')
      } catch (error) {

      }
    },
    // 删除
    async del({ order_id } = {}) {
      this.asyncMsg(async(instance, done) => {
        instance.confirmButtonLoading = true
        try {
          await delOrder({ order_id: order_id ? [order_id] : this.delIds })
          if (order_id) {
            this.list = this.list.filter(item => item.order_id !== order_id)
            this.page.total--
          } else {
            this.list = this.list.filter(item => !this.delIds.includes(item.order_id))
            this.page.total -= this.delIds.length
          }
          this.delIds = []
          done()
        } catch (error) {

        } finally {
          instance.confirmButtonLoading = false
        }
      })
    },
    // 修改支付时间
    async updatePayat({order_id, payment_at_copy}) {
      if (!payment_at_copy) return this.$message({ message: this.$t('order.payat_err'), type: 'warning' })
      try {
        this.curId = order_id
        this.isLoadPayat = true
        await editPaymentat({ order_id, payment_at: payment_at_copy })
        this.list.find(item => item.order_id === order_id).payment_at = payment_at_copy
        this.$message({ message: this.$t('common.success'), type: 'success' })
      } catch (error) {

      } finally {
        this.isLoadPayat = false
      }
    }
  }
}
</script>

<style lang="scss">
.txt {
  width: 80px;
  margin-left: 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.goods {
  // display: flex;
  .goods-title {
    font-weight: bold;
  }
  .goods-txt {
    margin: 5px 0;
    font-size: 12px;
  }
  .btns {
    display: flex;
    justify-content: center;
  }
}
.row-control-item {
  margin: 0 5px;
}
</style>
